import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { Store } from '@ngrx/store';
import { EditorActions } from '../../..//app/state/editor/actions/editor-action';
import { FocusActions } from '../../state/focus/actions/focus-action';
import { ActiveModuleState } from '../../state/focus/modules/active-module';

@Directive({
  selector: '[elementClick]',
})
export class ElementClickDirective {
  constructor(
    private elementRef: ElementRef,
    // eslint-disable-next-line @ngrx/no-typed-global-store
    private _store: Store<ActiveModuleState>
  ) {}

  // eslint-disable-next-line @typescript-eslint/member-ordering
  @Input()
  elementClick!: string;

  @HostListener('document:click', ['$event', '$event.target'])
  public onElementClick(event: PointerEvent, targetElement: HTMLElement): void {
    const graphOption:HTMLElement = document.getElementById('GRAPH_OPTION')
    if (!targetElement) {
      return;
    } else {
      const clickedInside =
        this.elementRef.nativeElement.contains(targetElement);
      if (clickedInside) {
        console.log('点击内部');
        console.log(targetElement);
        console.log(this.elementClick);
        // eslint-disable-next-line no-underscore-dangle
        this._store.dispatch(
          FocusActions.focusChange({ payload: { module: this.elementClick } })
        );
      } else {
        console.log('点击外部');
        console.log(targetElement);
        if (!(targetElement instanceof HTMLCanvasElement) && !(graphOption.contains(targetElement))) {
          // eslint-disable-next-line no-underscore-dangle
          this._store.dispatch(
            EditorActions.selectChange({ payload: { type: 'CANVAS', obj: {} } })
          );
        }

        this._store.dispatch(
          FocusActions.focusChange({ payload: { module: this.elementClick } })
        );
      }
    }
  }
}
